package com.qcby.admin.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class AliOSSUtils {
    private String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId="LTAI5t6HZqg2bNixh5Hr5uqz";
    private String accessKeySecret="82qRssIfmQo05j0haZPleiitkQ6LID";
    private String bucketName="blog27";


    /*
    * 实现上传图片到OSS
    */
    public String upload(MultipartFile multipartFile) throws IOException {
        //获取上传的文件的输入流
        InputStream inputStream=multipartFile.getInputStream();
        //避免文件覆盖
        String fileName= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+multipartFile.getOriginalFilename();
        System.out.println(fileName);
        //上传文件到OSS
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);
        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        //关闭ossClient
        ossClient.shutdown();
        return url;
    }
}
